package com.tanhua.server.interceptor;

import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.commons.utils.UserHolder;
import com.tanhua.domain.User;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Token统一处理
 */
public class TokenInterceptor implements HandlerInterceptor {
    /**
     * 请求到达controller前处理
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token
        String token = request.getHeader("Authorization");
        //判断token是否有效
//        if(!JwtUtils.verifyToken(token)){
//            //token失效，返回状态码401，并拦截
//            response.setStatus(401);
//            return false;
//        }
        //如果token正常，取出用户并将用户存入ThreadLocal，放行
        Claims claims = JwtUtils.getClaims(token);
        String mobile = (String) claims.get("mobile");
        Integer id = (Integer) claims.get("id");

        User user = new User();
        user.setId(Long.valueOf(id));   //将Integer转为Long
        user.setMobile(mobile);

        UserHolder.set(user);
        return true;
    }
}
